﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using HZ.MBSM.DBUtility;
using System.Text;

public partial class Bidder_BackGoods_detail : System.Web.UI.Page
{
    string strSql, BackPlanId, _strAccountId_PS, buystate;
    protected void Page_Load(object sender, EventArgs e)
    {
        BackPlanId = SysFun.IsSQL(SysFun.ToTrim(Request.QueryString["BackPlanId"]));
        // _strProjectId = SysFun.ToTrim(Request.QueryString["projectid"]); 2007/08/22 马


        System.Collections.Generic.List<HZ.MBSM.DAL.AccountType> _AccountType = new System.Collections.Generic.List<HZ.MBSM.DAL.AccountType>();
        _AccountType.Add(HZ.MBSM.DAL.AccountType.enumCompany);

        if (HZ.MBSM.BLL.Login.CheckAssert(_AccountType))
        {
            HZ.MBSM.Model.Account _Account = (HZ.MBSM.Model.Account)Session["Account"];
            _strAccountId_PS = SysFun.ToTrim(_Account.AccountId);
            if (!IsPostBack)
            {
                listDealStatus.Items.Add("全部");
                listDealStatus.Items.Add("未确认");
                listDealStatus.Items.Add("确认退货");

                Db db = new Db();
                System.Data.IDataReader dr;
                strSql = "select hospital.hospitalname,backplan.* from BackPlan,hospital where BackPlanId=" + BackPlanId + " and hospital.accountid=backplan.accountid_yy";
                dr = db.DataReader(strSql);
                if (dr.Read())
                {
                    LabHospital.Text = SysFun.ToTrim(dr["HospitalName"]);
                    txtStartTime.Text = Convert.ToDateTime(dr["StartTime"]).ToShortDateString();
                    txtPlanName.Text = SysFun.ToTrim(dr["PlanName"]);
                    rdoBuyStatus.SelectedValue = SysFun.ToTrim(dr["BuyStatus"]);
                    txtRemarks.Text = SysFun.ToTrim(dr["Remarks"]);
                    buystate = SysFun.ToTrim(dr["BuyStatus"]);
                }
                else
                {
                    Response.Write("对不起，你没有权限浏览不属于自身采购单的药品");
                    Response.End();
                }
                dr.Close();
                dr.Dispose();
                db.Close();
            }


            if (Request.Form["submitSave"] == "确定退货" && Request.Form["chk"] != null)
            {
                string _strBuyPlanGoodsId = SysFun.ToTrim(Request.Form["chk"]);

                Db db = new Db();
                if (_strBuyPlanGoodsId != "")
                {
                    // string[] _strArrayBuyPlanGoodsId = _strBuyPlanGoodsId.Length == 0 ? new string[] { "" } : _strBuyPlanGoodsId.Substring(0).Split(new char[] { ',' });
                    //string _strSql = "";
                    // string serSql = "";

                    // 判断是否结算
                    //string chkSql = "select buyplangoodsid from buyPlanGoods where buyplangoodsid in (" + _strBuyPlanGoodsId.Substring(0).ToString() + ") and ispayment=0";
                    //System.Data.IDataReader dr;
                    //dr = db.DataReader(chkSql);
                    //while (dr.Read())
                    //{
                    //    serSql += dr["buyplangoodsid"].ToString() + ",";

                    //}
                    //dr.Close();
                    //dr.Dispose();
                    //serSql = serSql == "" ? "" : serSql.Substring(0, serSql.Length - 1);
                    //string[] serSqlArray = serSql.Length == 0 ? new string[] { "" } : serSql.Substring(0).Split(new char[] { ',' });

                    //for (int i = 0; i < _strArrayBuyPlanGoodsId.Length; i++)
                    //{

                    //    _strSql += "@" + "update BackPlanGoods set backstate='1' where BackPlanGoodsId=" + _strArrayBuyPlanGoodsId[i].ToString();
                    //}
                    //if (_strSql.Length > 0)
                    //{
                    //    db.ExecuteTransaction(_strSql.Substring(1).Split(new char[] { '@' }), 30);
                    //}

                    //计算是否该数据已结款

                    //退货后修改库存量
                    //未结款退货更新库存量
                    string _strSql = "update buyPlanGoods set buyPlanGoods.ReturnState=2,buyPlanGoods.InflowNumStock = buyPlanGoods.InflowNumStock-backplangoods.backnum "
                         + "from backplangoods inner join  buyPlanGoods on (buyPlanGoods.buyplangoodsid = backplangoods.buyplangoodsid) where buyPlanGoods.ReturnState=1 and backPlanGoods.backplangoodsid in (" + _strBuyPlanGoodsId + ") and (isnull(buyPlanGoods.ispayment,0)=0)   and backplangoods.backplanid =  " + this.Request.QueryString["BackPlanId"].ToString()
                        //--未结款退货
                         + "; update backPlanGoods set backplangoods.payflag = 1,backstate='1' "
                         + " from backplangoods inner join  buyPlanGoods on (buyPlanGoods.buyplangoodsid = backplangoods.buyplangoodsid) where backPlanGoods.backplangoodsid in (" + _strBuyPlanGoodsId + ") and (isnull(buyPlanGoods.ispayment,0)=0) and backplangoods.backplanid = " + this.Request.QueryString["BackPlanId"].ToString()
                        //结款退货    
                         + "; update backPlanGoods set backplangoods.payflag = 2,backstate='1' from "
                         + " backplangoods inner join  buyPlanGoods on (buyPlanGoods.buyplangoodsid = backplangoods.buyplangoodsid) where backPlanGoods.backplangoodsid in (" + _strBuyPlanGoodsId + ") and buyPlanGoods.ispayment=1 and backplangoods.backplanid = " + this.Request.QueryString["BackPlanId"].ToString();
                    db.Command(_strSql);

                }

                db.Close();
                db = null;

            }
            //确定配送-->

            showGridView();
        }
    }

    public void showGridView()
    {
        int i = 0;
        Db db = new Db();
        DbPage dbPage = new DbPage(db);
        dbPage.Table = "BackGoodsView";                                               //要查询的表明
        dbPage.Key = "BackPlanGoodsId";                                               //表的主键    
        dbPage.Where = strcheck();                                                  //查询条件    
        dbPage.SelectField = "PurchasePrice,ReturnState,Case  When BackState=0 Then '未确认' When BackState is null Then '未确认' WHEN BackState=1 Then '确认退货' END AS BackState,"
                            + " BackPlanGoodsId,BuyPlanGoodsId,InflowNum,BackNum,GoodsNum,SupplyGoodsId,GoodsId,"
                            + " Case DealStatus When '0' Then '未确认送货' WHEN '1' Then '确认送货' WHEN '2' then '确认入库' WHEN '3' then '退货' END AS DealStatus,"
                            + " ProductCode,ProductName,MedicineModel,Outlookc,ProjectId,Factor,CompanyName_SC,UserCode_SC,CompanyName_TB,CompanyName_PS,TradePrice,"
                            + " Case GoodsState When '0' Then '原挂网' WHEN '1' Then '备案采购商品' WHEN '2' then '不限价不竞价商品' END AS GoodsState,"
                            + " GoodsName,Outlookc+'×'+convert(varchar(20),Factor)+unit As Pack1,"
                            + " case QualityLevels " + ConfigurationManager.AppSettings["QualityLevels"].ToString() + " end as QualityLevels,batchnumber,validityDate,BackBecause";//要显示的字段
        dbPage.PageIndex = SysFun.ToInt(Request["CurrentlyPageIndex"]);          //要显示第几页   
        dbPage.PageSize = 10;                                                    //没有显示记录条数   
        dbPage.OrderBy = "ProductName,MedicineModel,Outlookc,BackPlanGoodsId";//排序字段
        System.Text.StringBuilder strHtml = new System.Text.StringBuilder();
        strHtml.Append("<table width='100%'id='tabData' border='0.5' align='right' cellpadding='2' cellspacing='1'>");
        strHtml.Append("<tr>");
        strHtml.Append("<td width='8%'>商品<br/>流水号</td>");
        strHtml.Append("<td  width='8%'>通用名</td>");
        strHtml.Append("<td  width='5%'>商品名</td>");
        strHtml.Append("<td  nowrap>剂型</td>");
        // strHtml.Append("<td  nowrap>规格</td>");
        //strHtml.Append("<td  width='5%'>转换<br/>系数</td>");
        strHtml.Append("<td>包装规格</td>");
        strHtml.Append("<td  >质量<br/>层次</td>");
        strHtml.Append("<td  >交易价</td>");
        strHtml.Append("<td  >退货量</td>");
        strHtml.Append("<td  >退货批号</td>");
        strHtml.Append("<td  >药品<br/>有效期</td>");
        strHtml.Append("<td  >退货原因</td>");
        strHtml.Append("<td  >退货状态</td>");
        strHtml.Append("<td  width='9%'>生产企业</td>");
        strHtml.Append("<td  width='9%'>生产企业<br/>注册号</td>");
        //strHtml.Append("<td  >采购量</td>");
        //strHtml.Append("<td  >实际入库量</td>");
        //strHtml.Append("<td  >采购总金额</td>");
        strHtml.Append("<td nowrap>选择</td>");
        strHtml.Append("</tr>");
        System.Data.IDataReader dr = dbPage.ExecuteReader();

        while (dr.Read())
        {
            if (i == 0)
            {
                strHtml.Append("<tr class='table_td'>");
                i++;
            }
            else
            {
                strHtml.Append("<tr class='table_td2'>");
                i--;
            }
            strHtml.Append("<td width='8%'>" + dr["GoodsId"].ToString() + "</td>");
            strHtml.Append("<td width='8%'>" + dr["ProductName"].ToString() + "</td>");
            strHtml.Append("<td width='5%'>" + dr["GoodsName"].ToString() + "</td>");
            strHtml.Append("<td>" + dr["Medicinemodel"].ToString() + "</td>");
            //   strHtml.Append("<td>" + dr["Outlookc"].ToString() + "</td>");
            //  strHtml.Append("<td width='5%'>" + dr["Factor"].ToString() + "</td>");
            strHtml.Append("<td>" + dr["Pack1"].ToString() + "</td>");
            strHtml.Append("<td>" + dr["QualityLevels"].ToString() + "</td>");
            strHtml.Append("<td>" + SysFun.OutNum(dr["TradePrice"].ToString(), 3) + "</td>");
            strHtml.Append("<td>" + SysFun.ToTrim(dr["BackNum"]) + "</td>");
            strHtml.Append("<td>" + SysFun.ToTrim(dr["batchnumber"]) + "</td>");
            strHtml.Append("<td>" + SysFun.ToTrim(dr["validityDate"]) + "</td>");
            strHtml.Append("<td>" + SysFun.ToTrim(dr["BackBecause"]) + "</td>");
            strHtml.Append("<td>" + SysFun.ToTrim(dr["Backstate"]) + "</td>");
            strHtml.Append("<td>" + dr["CompanyName_SC"].ToString() + "</td>");
            strHtml.Append("<td>" + dr["UserCode_SC"].ToString() + "</td>");
            //strHtml.Append("<td>" + SysFun.ToTrim(dr["GoodsNum"]) + "</td>");
            //strHtml.Append("<td>" + SysFun.ToTrim(dr["InflowNum"]) + "</td>");
            //strHtml.Append("<td>" + dr["PurchasePrice"].ToString() + "</td>");
            if (dr["ReturnState"].ToString() == "2")
            {
                strHtml.Append("<td>已认定</td>");
            }
            else
            {
                strHtml.Append("<td><input name='chk' type='checkbox' value='" + dr["BackPlanGoodsId"].ToString() + "'></td>");
            }
            strHtml.Append("</tr>");
        }
        strHtml.Append("</table>");
        Lablist.Text = strHtml.ToString();

        //GridView1.DataSource = dr;
        //GridView1.DataBind();
        dr.Close();
        dr.Dispose();
        dbPage.Db.Close();
        db.Close();
        this.DbPageFlip1.DbPage = dbPage;//将数据传给控键

    }



    /// <summary>
    /// 绑定需要打印的数据源

    /// </summary>
    private void getPrintSource()
    {
        string sql = "select GoodsId as 商品流水号,productname as 通用名,goodsname as 商品名,medicinemodel as 剂型," +
            "Outlookc+'×'+convert(varchar(20),Factor)+unit As 包装规格,case QualityLevels " + ConfigurationManager.AppSettings["QualityLevels"].ToString() + " end as 质量层次," + "TradePrice as 交易价,BackNum as 退货数量,batchnumber as 药品批号,validityDate as 有效期," +
            "BackBecause as 退货原因,Case  When BackState=0 Then '未确认' When BackState is null Then '未确认' WHEN BackState=1 Then '确认退货' END AS 退货状态," +
            "CompanyName_SC as 生产企业,UserCode_SC as 生产企业注册号" +
            " from BackGoodsView where ";
        sql += strcheck();
        sql += " order by ProductName,MedicineModel,Outlookc,BackPlanGoodsId";
        Db db = new Db();
        DataTable dt = db.DataTable(sql);
        this.gvList.DataSource = dt;
        this.gvList.DataBind();
        db.Close();
    }

    /// <summary>
    /// 保存为excel文件
    /// </summary>
    private void ImportExcel()
    {
        getPrintSource();
        if (gvList.Rows.Count > 0)
        {
            gvList.Visible = true;
            Response.Clear();
            Response.ContentType = "application/x-excel";
            Response.AddHeader("content-disposition", "attachment;filename=\"" + System.Web.HttpUtility.UrlEncode("配送单" + DateTime.Now.ToShortDateString(), System.Text.Encoding.UTF8) + ".xls\"");
            Response.Charset = "GB2312";
            Response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");
            StringBuilder sb = new StringBuilder();
            System.IO.StringWriter stringWrite = new System.IO.StringWriter(sb);
            System.Web.UI.HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite);
            sb.Append(@"<style> .text { mso-number-format:\@; } </style> ");
            sb.Append("<html><body>");
            gvList.RenderControl(htmlWrite);
            sb.Append("</body></html>");
            Response.Write(stringWrite.ToString());
            Response.End();
            gvList.DataSource = null;
            gvList.Dispose();
        }
        else
        {
            Response.Write("<script>alert('没有信息,无法打印!')</script>");
        }
    }

    public override void VerifyRenderingInServerForm(Control control)
    {
    }

    private string strcheck()  //查询条件
    {
        //string _strTemp = " projectid=" + _strProjectId + " and BackPlanId=" + BackPlanId + " and Accountid_PS=" + _strAccountId_PS + " and";
        // 2007/08/22 马

        string _strTemp = " BackPlanId=" + BackPlanId + " and Accountid_PS=" + _strAccountId_PS + " and";

        //通用名

        string _strProductName = txtProductName.Text.ToString();
        if (_strProductName != "")
        {
            _strTemp += "   ( ProductName like '%" + _strProductName + "%' or Product_SpellingCode like '%" + _strProductName + "%' )  and";
        }

        //剂型
        string _strMedicinemodel = txtMedicinemodel.Text.ToString();
        if (_strMedicinemodel != "")
        {
            _strTemp += " medicinemodel like '%" + _strMedicinemodel + "%' and";
        }

        //规格
        string _strOutlookc = txtOutlook.Text.ToString();
        if (_strOutlookc != "")
        {
            _strTemp += " outlookc like '%" + _strOutlookc + "%' and";
        }

        //商品名

        string _strGoodsName = txtGoodsName.Text.ToString();
        if (_strGoodsName != "")
        {
            _strTemp += " goodsname like '%" + _strGoodsName + "%' and";
        }

        //商品流水号

        string _GoodsId = txtGoodsId.Text.ToString();
        if (_GoodsId != "")
        {
            _strTemp += " GoodsId =" + _GoodsId + " and";
        }

        //生产企业名称
        string _strCompanyNameSC = txtCompanyNameSC.Text.ToString();
        if (_strCompanyNameSC != "")
        {
            _strTemp += " CompanyName_SC like '%" + _strCompanyNameSC + "%' and";
        }

        //生产企业编码
        string _UserCodeSC = txtUserCodeSC.Text.ToString();
        if (_UserCodeSC != "")
        {
            _strTemp += " UserCode_SC like '%" + _UserCodeSC + "%' and";
        }

        //配送状态

        //BackState When 0 Then '未确认' WHEN 1 Then '确认退货'
        string _strDealStatus = listDealStatus.SelectedValue;
        switch (_strDealStatus)
        {
            case "全部":
                break;
            case "未确认":
                _strTemp += " (BackState=0 or BackState is null) and";
                break;
            case "确认退货":
                _strTemp += " BackState=1 and";
                break;
        }

        if (_strTemp != "")
        {
            _strTemp = "  " + _strTemp.Substring(0, _strTemp.Length - 3);
        }

        return _strTemp;
    }



    protected void Button1_Click(object sender, EventArgs e)
    {
        ImportExcel();
    }
}
